import React, { useState } from "react";
import {
  Modal,
  Form,
  Input,
  Button,
  Checkbox,
  Space,
  Select,
  DatePicker,
  Upload,
  message,
} from "antd";
import moment from "moment";
import { connect } from "react-redux";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}

function beforeUpload(file) {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("You can only upload JPG/PNG file!");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("Image must smaller than 2MB!");
  }
  return isJpgOrPng && isLt2M;
}

function ModalBox(props) {
  const { isModalVisible, setIsModalVisible, title, val } = props;
  const [form] = Form.useForm();
  const [imageUrl, setimageUrl] = React.useState("");
  const [loading, setLoading] = React.useState(false);

  React.useEffect(() => {
    let nval = { ...val };
    nval.date = nval.date ? moment(nval.date) : "";
    if (!Array.isArray(nval.hobby)) {
      let arr = [];
      for (const key in nval.hobby) {
        arr.push(nval.hobby[key]);
        console.log(key, nval.hobby[key]);
      }
      nval.hobby = arr;
    }
    form.setFieldsValue({ ...nval });
    setimageUrl(nval.imageUrl);
  }, [val]);

  // 提交按钮
  const submitFn = () => {
    form.validateFields().then((values) => {
      values.date = moment(values.date).format("YYYY-MM-DD");

      if (values.id) {
        let nlist = props.antdList.list.map((v) => {
          if (v.id === values.id) {
            v = values;
          }
          return v;
        });
        props.setList(nlist);
        setIsModalVisible(false);
        form.resetFields();
      } else {
        values.id = props.antdList.list[props.antdList.list.length - 1].id + 1;
        let list = props.antdList.list;

        list.push(values);
        props.setList(list);
        setIsModalVisible(false);
        form.resetFields();
      }
      setimageUrl("");
    });
  };

  // 取消按钮
  const cancelFn = () => {
    setIsModalVisible(false);
    form.resetFields();
    setimageUrl("");
  };

  // 关闭按钮
  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
    setimageUrl("");
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  const handleChange = (info) => {
    console.log(info);
    if (info.file.status === "uploading") {
      setLoading(true);
    }
    if (info.file.status === "done") {
      const {
        response: {
          data: { msbox },
        },
      } = info.file;
      setLoading(false);
      let images = "http://vueshop.glbuys.com/userfiles/head/" + msbox;
      console.log(images);
      setimageUrl(images);
      form.setFieldsValue({ imageUrl: images });
    }
  };

  return (
    <Modal
      title={title}
      visible={isModalVisible}
      footer
      onCancel={handleCancel}
      forceRender
    >
      <Form
        form={form}
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        initialValues={{ remember: true }}
        autoComplete="off"
      >
        <Form.Item label="id" name="id">
          <Input />
        </Form.Item>

        <Form.Item
          label="name"
          name="name"
          rules={[{ required: true, message: "Please input your name!" }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="age"
          label="age"
          hasFeedback
          rules={[
            {
              required: true,
              message: "Please select your age!",
            },
          ]}
        >
          <Select placeholder="Please select a age">
            {Array.from(new Array(50), (v, i) => {
              return (
                <Select.Option key={i + 20} value={i + 20}>
                  {i + 20}
                </Select.Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item
          name="address"
          label="address"
          hasFeedback
          rules={[
            {
              required: true,
              message: "Please select your address!",
            },
          ]}
        >
          <Select placeholder="Please select a address">
            <Select.Option value="山西">山西</Select.Option>;
            <Select.Option value="河北">河北</Select.Option>;
            <Select.Option value="石家莊">石家莊</Select.Option>;
            <Select.Option value="北京">北京</Select.Option>;
            <Select.Option value="上海">上海</Select.Option>;
            <Select.Option value="天津">天津</Select.Option>;
          </Select>
        </Form.Item>

        <Form.Item
          name="date"
          label="date"
          hasFeedback
          rules={[
            {
              required: true,
              message: "Please select your date!",
            },
          ]}
        >
          <DatePicker />
        </Form.Item>

        <Form.Item
          name="hobby"
          label="hobby"
          hasFeedback
          rules={[
            {
              required: true,
              message: "Please select your hobby!",
            },
          ]}
        >
          <Select placeholder="Please select a hobby" mode="multiple">
            <Select.Option value="干饭">干饭</Select.Option>;
            <Select.Option value="敲代码">敲代码</Select.Option>;
            <Select.Option value="追剧">追剧</Select.Option>;
            <Select.Option value="金铲铲">金铲铲</Select.Option>;
          </Select>
        </Form.Item>

        <Form.Item label="img">
          <Form.Item name="imageUrl" noStyle>
            <Input />
          </Form.Item>
          <Upload
            name="headfile"
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            action="http://vueshop.glbuys.com/api/user/myinfo/formdatahead?token=1ec949a15fb709370f"
            beforeUpload={beforeUpload}
            onChange={handleChange}
          >
            {imageUrl ? (
              <img src={imageUrl} alt="" style={{ width: "100%" }} />
            ) : (
              uploadButton
            )}
          </Upload>
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Space>
            <Button onClick={submitFn}>Submit</Button>
            <Button onClick={cancelFn}>cancel</Button>
          </Space>
        </Form.Item>
      </Form>
    </Modal>
  );
}
export default connect(({ antdList }) => ({ antdList }), {
  // setListasync,
  setList(payload) {
    return { type: "set_list", payload };
  },
})(ModalBox);
